package com.crypt.properties.algorithm.aes;

import com.crypt.properties.CryptProperties;
import com.crypt.properties.algorithm.AbstractCryptAlgorithm;
import com.crypt.properties.exception.CryptPropertiesException;
import com.crypt.properties.util.Aes;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class AESCryptAlgorithm extends AbstractCryptAlgorithm {

    @Override
    public String getAlg() {
        return "AES/CBC/PKCS7Padding";
    }

    @Override
    public String decrypt(String value) {
        String key = String.valueOf(this.properties.getOrDefault(CryptProperties.aesKey, ""));
        if (key == null || key.length() == 0) {
            throw new CryptPropertiesException("Aes secret key is required. set \"" + CryptProperties.aesKey + "\" value at \"application.properties\" or \"application.yml\"");
        }
        String iv = String.valueOf(this.properties.getOrDefault(CryptProperties.aesIv, ""));
        if (iv == null || iv.length() == 0) {
            throw new CryptPropertiesException("Aes CBC mode iv parameter is required. set \"" + CryptProperties.aesIv + "\" value at \"application.properties\" or \"application.yml\"");
        }
        try {
            Aes aes = new Aes(key, iv);
            return aes.decrypt(value);
        } catch (UnsupportedEncodingException | NoSuchPaddingException | InvalidAlgorithmParameterException | InvalidKeyException | BadPaddingException | IllegalBlockSizeException | NoSuchAlgorithmException e) {
            throw new CryptPropertiesException(e.getMessage(), e);
        }
    }
}
